'''
Function:
    运行game
author:
    walker
time:
    2020/5/14
'''
import sys
from config import *
from game import *
from game_parser import *
from cells import *
from player import *
from grid import *

'''给cells初始化'''
def init_cells(all_cells_lists):
    all_sprites_list = []

    for i in range(len(all_cells_lists)-1):
        list_item = []
        for j in range(len(all_cells_lists[i])):
            list_item.append(Cell(all_cells_lists[i][j]))
        all_sprites_list.append(list_item)

    return all_sprites_list

'''主函数'''
def main():
    load_level = Game_parse()
    level_str_list = load_level.read_txt(LEVEL1)
    draw_ori_level(level_str_list)
    grid = load_level.parse(level_str_list)

    # 获取到每个cell的坐标及其display
    all_cells_lists,all_cells_lists_pos = record_cells_info(grid)
    # 将每个cell给实例化为其对应的精灵
    all_sprites_list = init_cells(all_cells_lists)
    acorn_sprites = Player(all_cells_lists[-1][0],0)
    acorn_sprites.ori_display = 'X'

    #获取到水火的list
    water_lists = all_cells_lists_pos[4]
    fire_lists = all_cells_lists_pos[5]

    #先将起始点覆盖
    level_str_list_copy = cover_start_to_A(level_str_list,all_cells_lists[-1])
    print("### Output ###")
    for level_str_list_copy_item in level_str_list_copy:
        print(level_str_list_copy_item)
    # 统计每一步
    print("You have 0 water buckets.")
    print("")
    step_list = []
    running = True
    # os.system("cls")
    while running:
        # 检测非法输入
        move = None
        try:
            move = input('Input a move:')
            if move not in INPUT_LIST:
                raise ValueError("Please enter a valid move (w, a, s, d, e, q).")
            else:
                acorn_sprites_ori_pos = [acorn_sprites.row,acorn_sprites.col]
                acorn_sprites,is_exit,is_move = check_move(level_str_list,acorn_sprites,move,all_cells_lists_pos[0])

                #如果到达终点，则胜利
                if acorn_sprites.row == all_cells_lists_pos[3][0][0] and acorn_sprites.col == all_cells_lists_pos[3][0][1]:
                    win_lose(acorn_sprites,'YOU WIN')
                    running = False
                    break
                #如果输入的是esc键，则直接退出游戏
                if is_exit == True:
                    win_lose(acorn_sprites,'YOU LOSE')
                    running = False
                    break

                # #遇见水就将水给保存
                # if acorn_sprites_ori_pos in water_lists:
                #     acorn_sprites.num_water_buckets += 1
                #     poped_water_pos = water_lists.pop(water_lists.index([acorn_sprites.row,acorn_sprites.col]))
                #     grid_str_list_row = list(grid_str_list[acorn_sprites.row])
                #     grid_str_list_row[acorn_sprites.col] = 'X'
                #     grid_str_list_row = ''.join(grid_str_list_row)
                #     grid_str_list[all_cells_lists_pos[2][0][0]] = grid_str_list_row

                #遇见火如果有水则将火给浇灭，没有则失败
                if [acorn_sprites.row,acorn_sprites.col] in fire_lists:
                    if acorn_sprites.num_water_buckets >= 1:
                        acorn_sprites.num_water_buckets -= 1
                    else:
                        win_lose(acorn_sprites,'YOU LOSE')
                        running = False
                        break

                grid = []
                for level_str_list_item in level_str_list:
                    grid_str_list_row = list(level_str_list_item)
                    grid.append(grid_str_list_row)
                    
                grid_process = Grid()
                grid_str_list,num_water_buckets = grid_process.grid_to_string(grid,acorn_sprites)
                # 将返回的地图字符串按照\n来切片，并且截取[:-1]这一段当作地图
                grid_str_list = grid_str_list.split('\n')[:-1]

                #刷新入口
                if all_cells_lists_pos[2][0] != [acorn_sprites.row,acorn_sprites.col]:
                    grid_str_list_row = list(grid_str_list[all_cells_lists_pos[2][0][0]])
                    grid_str_list_row[all_cells_lists_pos[2][0][1]] = 'X'
                    grid_str_list_row = ''.join(grid_str_list_row)
                    grid_str_list[all_cells_lists_pos[2][0][0]] = grid_str_list_row

                #刷新传送门
                for trans_item in all_cells_lists_pos[6]:
                    index = all_cells_lists_pos[6].index(trans_item)
                    trans_num = all_cells_lists[6][index][2]
                    if trans_item != [acorn_sprites.row,acorn_sprites.col]:
                        # print("还没有到突然送到")
                        grid_str_list_row = list(grid_str_list[trans_item[0]])
                        grid_str_list_row[trans_item[1]] = trans_num
                        grid_str_list_row = ''.join(grid_str_list_row)
                        grid_str_list[trans_item[0]] = grid_str_list_row
                    else:
                        # print("到传送点了")
                        for grid_str_list_item in grid_str_list:
                            print(grid_str_list_item)
                        print("Whoosh! The magical gates break Physics as we know it and opens a wormhole through space and time.")
                        trans_flag = input("Press 'e' to start crossing or press 'w','a','s','d' to quit:  ")
                        if trans_flag == 'e':
                            acorn_sprites,level_str_list = player_trans(acorn_sprites,grid_str_list,trans_num)



                for grid_str_list_item in grid_str_list:
                    print(grid_str_list_item)
                print("You have %d water buckets."%acorn_sprites.num_water_buckets)
                # process_move(acorn_sprites,level_str_list_copy,all_cells_lists_pos)

        except:
            raise ValueError("Sorry, an unknown error has occurred:)")


if __name__ == '__main__':
    main()
